/*
 * @Version: 0.0.1
 * @Author: ider
 * @Date: 2021-01-05 15:03:39
 * @LastEditors: ider
 * @LastEditTime: 2021-01-07 22:12:43
 * @Description:
 */
package shared

import (
	"fmt"
	"net/http"
	"reflect"
)

const (
	defaultCode = 1001
)

var CodeErrorType = reflect.TypeOf(CodeError{})

type CodeError struct {
	Code int    `json:"code"`
	Msg  string `json:"msg"`
}

func NewCodeError(code int, msg string) error {
	return &CodeError{Code: code, Msg: msg}
}

func NewDefaultError(msg string) error {
	return NewCodeError(defaultCode, msg)
}

func (e *CodeError) Error() string {
	return e.Msg
}

// 定义错误处理函数
func ErrorHandler(err error) (int, interface{}) {
	value := reflect.ValueOf(err)
	value = reflect.Indirect(value)

	//获取结构体s的类型S
	vt := value.Type()
	fmt.Println("vt", vt)

	// shared.CodeError

	switch vt { //v表示b1 接口转换成Bag对象的值
	case CodeErrorType:
		return http.StatusConflict, CodeError{
			Code: int(value.FieldByName("Code").Int()),
			Msg:  value.FieldByName("Msg").String(),
		}
	default:
		return http.StatusConflict, CodeError{
			Code: -1,
			Msg:  err.Error(),
		}
	}
}
